import { defineStore } from "pinia";
import { fetchCartList, updateCartItemByCartId, removeCartItemByCartId, removeCartItemByCartIdList } from "@/api/cart";
import { getBookDetail } from "@/api/book";

export const useCartStore = defineStore("cart", {
  state: () => ({
    cartList: [],
  }),
  getters: {
    // 获取带详情的购物车列表（过滤掉无详情的项）
    cartListWithDetails: (state) =>
      state.cartList.filter(item => item.bookDetail)
  },
  actions: {
    async addCartList(userId) {
      try {
        // 获取购物车基础列表
        const response = await fetchCartList(userId);
        const cartBaseList = response.data.data || [];

        // 并行获取所有书籍详情（关键修复点）
        const cartWithDetails = await Promise.all(
          cartBaseList.map(async (item) => {
            try {
              const bookDetailResponse = await getBookDetail(item.bookId);


              return {
                ...item,
                bookDetail: bookDetailResponse.data.data
              };
            } catch (bookError) {
              console.error(`获取书籍 ${item.bookId} 详情失败`, bookError);
              return {
                ...item,
                bookDetail: {
                  title: '未知图书',
                  price: 0,
                  coverUrl: '../assets/background.png',
                  description: '信息加载失败'
                }
              };
            }
          })
        );

        // 使用新数组更新购物车列表（确保响应式）
        this.cartList = cartWithDetails;
        console.log("获取购物车内容包含每一项内容详情：", this.cartList);

        return this.cartList;
      } catch (error) {
        console.error("获取购物车列表失败", error);
        throw error; // 向上抛出错误，由调用者处理
      }
    },

    async updateCartItem(cartId, quantity, userId) {
      try {
        // 更新服务器数据
        await updateCartItemByCartId(cartId, quantity);

        // 重新获取完整购物车列表（包含最新详情）
        return await this.addCartList(userId);
      } catch (error) {
        console.error("更新购物车数量失败", error);
        throw error;
      }
    },
    async RemoveCartItemByCartId(cartId) {
      try {
        const response = await removeCartItemByCartId(cartId);
        console.log("删除购物车响应结果", response);

      } catch (error) {
        console.error("删除购物车项失败", error);
        throw error;
      }
    },
    async RemoveCartItemByCartIdList(cartIdList) {
      try {
        const response = await removeCartItemByCartIdList(cartIdList);
        console.log("批量删除购物车响应结果!", response);


      } catch (error) {
        console.error("批量删除购物车项失败", error);
      }
    }










  }
});